package com.samuel.blog.utils;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.web.multipart.MultipartFile;

import com.samuel.blog.constant.CommonConstant;

/**
 * 图片上传
 * @author kaiji
 *
 */
public class ImageUtils {
	
	private static final Logger logger = Logger.getLogger(ImageUtils.class);

	/**
	 * 上传到本地静态服务器上
	 * @param file
	 * @return
	 * @throws IOException 
	 * @throws IllegalStateException 
	 */
	public static String uploadServer(MultipartFile file) throws IllegalStateException, IOException {
		String folderName = DateUtils.dateToStrWithFormat(new Date(), "yyyyMMdd");
		String uuid = UUID.randomUUID().toString().replaceAll("-", "");
		String contentType = file.getContentType();
		String imgSuffix = contentType.substring(contentType.indexOf("/")+1);
		logger.info("图片后缀是：" + imgSuffix);
		String newFileName = uuid+"."+imgSuffix;
		String url = CommonConstant.UPLOAD_URL+folderName+File.separator;
		logger.info("图片上传路径是：" + url);
		
		File uploadUrl = new File(url);
		if (!uploadUrl.isDirectory()) {
			uploadUrl.mkdirs();
		}
		File dest = new File(url+newFileName);
		file.transferTo(dest);
		logger.info("图片完整上传路径是：" + url+newFileName);
		logger.info("返回给页面的图片路径是：" + folderName+File.separator+newFileName);
		return CommonConstant.IMAGES_URL + File.separator+folderName+File.separator+newFileName;
	}
	
	
	/**
	 * 上传到本地项目上
	 * @param file
	 * @return
	 * @throws IOException 
	 * @throws IllegalStateException 
	 */
	public static String uploadLocalServer(HttpServletRequest request, MultipartFile file) throws IllegalStateException, IOException {
		String folderName = DateUtils.dateToStrWithFormat(new Date(), "yyyyMMdd");
		String uuid = UUID.randomUUID().toString().replaceAll("-", "");
		String contentType = file.getContentType();
		String imgSuffix = contentType.substring(contentType.indexOf("/")+1);
		logger.info("图片后缀是：" + imgSuffix);
		String newFileName = uuid+"."+imgSuffix;
		String realPath = request.getServletContext().getRealPath("image") + File.separator;
		String url = realPath+folderName+File.separator;
		logger.info("图片上传路径是：" + url);
		
		File uploadUrl = new File(url);
		if (!uploadUrl.isDirectory()) {
			uploadUrl.mkdirs();
		}
		File dest = new File(url+newFileName);
		file.transferTo(dest);
		logger.info("图片完整上传路径是：" + url+newFileName);
		logger.info("返回给页面的图片路径是：" + folderName+File.separator+newFileName);
		return File.separator+"image"+File.separator+folderName+File.separator+newFileName;
	}
	
	

}
